/**
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: ---Technology Co. Ltd</p>
 * <p>2014-4-30</p>
 * @author Jan.Zhang
 */
package com.xianl.busiplat.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.common.collect.Lists;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.xianl.busiplat.dwz.AjaxObject;
import com.xianl.busiplat.dwz.Page;
import com.xianl.busiplat.exception.ExistedException;
import com.xianl.busiplat.po.Role;
import com.xianl.busiplat.po.User;
import com.xianl.busiplat.po.UserRole;
import com.xianl.busiplat.service.GroupService;
import com.xianl.busiplat.service.RoleService;
import com.xianl.busiplat.service.UserRoleService;
import com.xianl.busiplat.service.UserService;
import com.xianl.busiplat.util.TimeUtils;


/** 
 * desc:
 * <p>author: Jan.Zhang </p>
 * date: 2014-4-30
 */
@Controller
@RequestMapping("/sys/core/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	UserRoleService userRoleService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private GroupService groupService;
	private static final String CREATE = "sys/core/user/create";
	private static final String UPDATE = "sys/core/user/update";
	private static final String LIST = "sys/core/user/list";
	private static final String LOOK_UP_ROLE = "sys/core/user/assign_role";
	private static final String LOOK_USER_ROLE = "sys/core/user/delete_user_role";
	private static final String LOOK_ORG = "sys/core/user/lookup_org";

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:06</p>
	 * @return
	 */
	@RequiresPermissions("User:save")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String preCreate() {
		return CREATE;
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:10</p>
	 * @param user
	 * @return
	 */
	@RequiresPermissions("User:save")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public @ResponseBody
	String create(User user, String _losedate, String _effdate) {
		AjaxObject ajaxObject = new AjaxObject("用户添加成功！");
		user.setInTime(new Date());
		user.setModTime(new Date());
		user.setEffDate(TimeUtils.formatStringToDate(_effdate, "yyyy-MM-dd"));
		user.setLoseDate(TimeUtils.formatStringToDate(_losedate, "yyyy-MM-dd"));
		if(!user.getLoseDate().after(user.getEffDate()) ) {
			ajaxObject.setMessage("失效日期要大于生效日期！");
			ajaxObject.setCallbackType("");
			ajaxObject.setStatusCode(AjaxObject.STATUS_CODE_FAILURE);
			return ajaxObject.toString();
		}
		try {
			userService.save(user);
		} catch (ExistedException e) {
			ajaxObject = new AjaxObject(e.getMessage());
			ajaxObject.setCallbackType("");
			ajaxObject.setStatusCode(AjaxObject.STATUS_CODE_FAILURE);
			return ajaxObject.toString();
		}
		ajaxObject.setCallbackType(AjaxObject.CALLBACK_TYPE_SMPRELOADLIST);
		ajaxObject.setForwardUrl(LIST);
		return ajaxObject.toString();
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:14</p>
	 * @param id
	 * @return
	 */
	@ModelAttribute("preloadUser")
	public User getOne(@RequestParam(value = "id", required = false) Long id) {
		if(id != null ) {
			User user = userService.get(id.intValue());
			return user;
		}
		return null;
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:17</p>
	 * @param id
	 * @param map
	 * @return
	 */
	@RequiresPermissions("User:edit")
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String preUpdate(@PathVariable Integer id, Map<String, Object> map) {
		User user = userService.get(id);
		map.put("_losedate", TimeUtils.formatTimestamp2String(user.getLoseDate(), "yyyy-MM-dd"));
		map.put("_effdate", TimeUtils.formatTimestamp2String(user.getEffDate(), "yyyy-MM-dd"));
		map.put("user", user);
		return UPDATE;
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:20</p>
	 * @param user
	 * @return
	 */
	@RequiresPermissions("User:edit")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody
	String update(@ModelAttribute("preloadUser") User user, String _losedate, String _effdate) {
		AjaxObject ajaxObject = new AjaxObject("用户修改成功！");
		user.setModTime(new Date());
		user.setEffDate(TimeUtils.formatStringToDate(_effdate, "yyyy-MM-dd"));
		user.setLoseDate(TimeUtils.formatStringToDate(_losedate, "yyyy-MM-dd"));
		if(!user.getLoseDate().after(user.getEffDate()) ) {
			ajaxObject.setMessage("失效日期要大于生效日期！");
			ajaxObject.setCallbackType("");
			ajaxObject.setStatusCode(AjaxObject.STATUS_CODE_FAILURE);
			return ajaxObject.toString();
		}
		userService.update(user);
		ajaxObject.setCallbackType(AjaxObject.CALLBACK_TYPE_SMPRELOADLIST);
		ajaxObject.setForwardUrl(LIST);
		return ajaxObject.toString();
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:22</p>
	 * @param id
	 * @return
	 */
	@RequiresPermissions("User:delete")
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	public @ResponseBody
	String delete(@PathVariable Integer id) {
		AjaxObject ajaxObject = new AjaxObject("用户删除成功！");
		if(id ==1){
			ajaxObject = new AjaxObject("该用户不可以删除！");
		}else{
			try {
				userService.delete(id);
			} catch (Exception e) {
				if(e instanceof MySQLIntegrityConstraintViolationException){
					ajaxObject.setMessage("删除用户前，请先删除该用户的所有权限！");
				}else{
					ajaxObject.setMessage(e.getMessage());
				}
			}
		}
		ajaxObject.setCallbackType("");
		return ajaxObject.toString();
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:26</p>
	 * @param page
	 * @param keywords
	 * @param map
	 * @return
	 */
	@RequiresPermissions("User:view")
	@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
	public String list(Page page, String keywords, Map<String, Object> map) {
		List<User> users;
		if(StringUtils.isNotBlank(keywords) ) {
			users = userService.find(page, map);
		} else {
			users = userService.findAll(null, page);
		}
		map.put("page", page);
		map.put("users", users);
		map.put("keywords", keywords);
		return LIST;
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:29</p>
	 * @param type
	 * @param userId
	 * @return
	 */
	@RequiresPermissions("User:edit")
	@RequestMapping(value = "/reset/{type}/{userId}", method = RequestMethod.POST)
	public @ResponseBody
	String reset(@PathVariable String type, @PathVariable Integer userId) {
		User user = userService.get(userId);
		AjaxObject ajaxObject = new AjaxObject();
		if(type.equals("password") ) {
			user.setPlainPassword("123456");
			ajaxObject.setMessage("重置密码成功，默认密码为123456！");
		} else if(type.equals("status") ) {
			if(user.getStatus() == 1 ) {
				user.setStatus(0);
			} else {
				user.setStatus(1);
			}
			ajaxObject.setMessage("更新状态为[ " + (user.getStatus() == 0 ? "可用" : "不可用") + " ]");
		}
		userService.update(user);
		ajaxObject.setCallbackType("");
		return ajaxObject.toString();
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:33</p>
	 * @param userRole
	 */
	@RequiresPermissions("User:save")
	@RequestMapping(value = "/create/userRole", method = {RequestMethod.POST})
	public @ResponseBody
	void assignRole(UserRole userRole) {
		userRoleService.save(userRole);
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:36</p>
	 * @param map
	 * @param userId
	 * @return
	 */
	@RequiresPermissions("User:edit")
	@RequestMapping(value = "/lookup2create/userRole/{userId}", method = {RequestMethod.GET, RequestMethod.POST})
	public String listUnassignRole(Map<String, Object> map, @PathVariable Integer userId) {
		Page page = new Page();
		page.setNumPerPage(Integer.MAX_VALUE);
		List<UserRole> userRoles = userRoleService.find(userId);
//		List<Role> roles = roleService.findAll(page);
		List<Role> hasList = Lists.newArrayList();
//		List<Role> allRoles = Lists.newArrayList(roles);
		// 删除已分配roles TODO
//		for(UserRole ur: userRoles) {
//			for(Role role: roles) {
//				if(ur.getRole().getId() == role.getId()) {
//					hasList.add(role);
//					break;
//				}
//			}
//		}
//		allRoles.removeAll(hasList);
		map.put("userRoles", userRoles);
//		map.put("roles", allRoles);
		map.put("userId", userId);
		return LOOK_UP_ROLE;
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:39</p>
	 * @param map
	 * @param userId
	 * @return
	 */
	@RequiresPermissions("User:edit")
	@RequestMapping(value = "/lookup2delete/userRole/{userId}", method = {RequestMethod.GET, RequestMethod.POST})
	public String listUserRole(Map<String, Object> map, @PathVariable Integer userId) {
		List<UserRole> userRoles = userRoleService.find(userId);
		map.put("userRoles", userRoles);
		return LOOK_USER_ROLE;
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:42</p>
	 * @param userRoleId
	 */
	@RequiresPermissions("User:edit")
	@RequestMapping(value = "/delete/userRole/{userRoleId}", method = {RequestMethod.POST})
	public @ResponseBody
	void deleteUserRole(@PathVariable Long userRoleId) {
//		userRoleService.delete(userRoleId);
	}

	/**
	 * desc: <p>创建人：Jan.Zhang , 2013-1-14 下午04:27:45</p>
	 * @param map
	 * @return
	 */
	@RequiresPermissions(value = {"User:edit", "User:save"})
	@RequestMapping(value = "/lookup2org", method = {RequestMethod.GET})
	public String lookup(Map<String, Object> map) {
//		Group org = groupService.getTree();
//		map.put("org", org);
		return LOOK_ORG;
	}
}
